#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>

#include "include/jpeglib.h"


int main(){
	int fd=0;

	fd=open("/dev/fb0",O_RDWR);
	if(fd<0){
		printf("open device error\n");
		return -1;
	}

	struct jpeg_decompress_struct cinfo;
        struct jpeg_error_mgr jerr;
        FILE *infile;
        unsigned char  *buffer;
        int x, y;

        unsigned char *tmp_buf;
        unsigned long size;
        int ret;

	 if((infile = fopen("4.jpg", "rb")) == NULL){
		printf("read file error\n");
                return -1;
        }

        cinfo.err = jpeg_std_error(&jerr);
        jpeg_create_decompress(&cinfo);

	fseek(infile, 0L, SEEK_END);
        size = ftell(infile);
        rewind(infile);

	tmp_buf = (unsigned char *)malloc(sizeof(char) * size);
        if (tmp_buf == NULL)
        {
                printf("malloc failed.\n");
                return -1;
        }
        ret = fread(tmp_buf, 1, size, infile);
        if (ret != size)
        {
                printf("read jpeg file error.\n");
                return -1;
        }

	jpeg_mem_src(&cinfo, tmp_buf, size);
 	jpeg_read_header(&cinfo, TRUE);
        jpeg_start_decompress(&cinfo);
	printf("width:%d height:%d\n",cinfo.output_width,cinfo.output_height);
        if ((cinfo.output_width > 1360) || (cinfo.output_height > 768)) {
                printf("too large JPEG file,cannot display\n");
                return -1;
        }

	buffer = (unsigned char *) malloc(cinfo.output_width * cinfo.output_components);
	x = y = 0;
	int fb_depth=32;
	unsigned int *bitbuf;
	bitbuf=(unsigned int *)mmap(NULL,1408*768*4,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
	if(bitbuf==NULL){
		printf("mmap error\n");
		return -1;
	}
	unsigned int color;
	while (cinfo.output_scanline < cinfo.output_height) {
                jpeg_read_scanlines(&cinfo, &buffer, 1);
		for(x=0;x<cinfo.output_width;x++){
			color=buffer[x*3+2]|(buffer[x*3+1]<<8)|(buffer[x*3]<<16);
			bitbuf[y*1408+x]=color;
		}
                y++;        // next scanline
        }

	jpeg_finish_decompress(&cinfo);
        jpeg_destroy_decompress(&cinfo);

        fclose(infile);

        free(tmp_buf);

        free(buffer);
	munmap(bitbuf,1408*768*4);
	close(fd);
        return 0;

}
